<?php
namespace App\DBs\Stock;

use Illuminate\Support\Facades\DB;

class PlusDB extends BaseDB
{
    /**
     * 创单
     * uid 用户UID
     * vid 视频ID
     * del 0未删除，1已删除
     */

    protected $table = 'stock_plus'; //库创单
    protected $tCollect = 'stock_collect'; //库收藏
    protected $tStock = 'stock'; //库
    protected $tBoard = 'stock_board'; //库创板
    protected $tSource = 'stock_source'; //库素材

    public function __construct()
    {
    }

    /**
     * 后台列表
     */
    public function getAdminIndex($page, $size, $vid, $uid)
    {
        $pageStart = $page * $size;
        $query = DB::table($this->table)
//            ->where('del',0)
            ->orderBy('id','desc');
        if ($vid) { $query = $query->where('vid',$vid); }
        if ($uid) { $query = $query->where('uid',$uid); }
        $queryTotal = $query->count();
        $models = $query->skip($pageStart)
            ->take($size)
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            //库视频信息
            $resStocks = DB::table($this->tStock)
//                ->where('del',0)
                ->where('id',$model['vid'])
                ->orderBy('id','desc')
                ->skip(0)->take(1)
                ->get();
            $stockOne = count($resStocks) ? $this->jsonToArr($resStocks[0]) : '';
            $stockTitle = $stockOne ? $stockOne['fileTitle'] : '';
            $stockImg = $stockOne ? $stockOne['fileImg'] : '';
            $stockLink = $stockOne ? $stockOne['originLink'] : '';
            $stockType = $stockOne ? $stockOne['fromType'] : '';
            //用户信息
            $resUser = $this->getUnameByUid($model['uid']);
            $dataArr[] = [
                'plusId' => $model['id'],
                'uid' => $model['uid'],
                'uname' => $resUser,
                'videoId' => $model['vid'],
                'videoTitle' => $stockTitle,
                'videoType' => $stockType,
                'videoImg' => $stockImg,
                'videoLink' => $stockLink,
                'del' => $model['del'],
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * 后台库视频
     */
    public function getAdminStocks()
    {
        $vids = array();
        $dataArr = array();
        $models = DB::table($this->table)
//            ->distinct('vid')
            ->orderBy('id','asc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据', 'data'=>$dataArr);
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            if (!in_array($model['vid'],$vids)) {
                $resStocks = DB::table($this->tStock)
                    ->where('id',$model['vid'])
                    ->orderBy('id','desc')
                    ->skip(0)->take(1)
                    ->get();
                $stockOne = count($resStocks) ? $this->jsonToArr($resStocks[0]) : '';
                $stockTitle = $stockOne ? $stockOne['fileTitle'] : '';
                $dataArr[] = [
                    'videoId' => $model['vid'],
                    'videoTitle' => $stockTitle,
                ];
                $vids[] = $model['vid'];
            }
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * 后台用户
     */
    public function getAdminUsers()
    {
        $uids = array();
        $dataArr = array();
        $models = DB::table($this->table)
//            ->distinct('uid')
            ->orderBy('id','asc')
            ->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据', 'data'=>$dataArr);
        }
        $models = $this->jsonToArr($models);
        foreach ($models as $model) {
            if (!in_array($model['uid'],$uids)) {
                $resUser = $this->getUnameByUid($model['uid']);
                $dataArr[] = [
                    'uid' => $model['uid'],
                    'uname' => $resUser,
                ];
                $uids[] = $model['uid'];
            }
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr);
    }

    /**
     * =====================================
     * 以下是APP
     * =====================================
     */

    /**
     * APP列表
     */
    public function getAppIndex($uid)
    {
        $query = DB::table($this->table)
            ->where('del',0)
            ->orderBy('id','desc');
        if ($uid) { $query = $query->where('uid',$uid); }
        $queryTotal = $query->count();
        $models = $query->get();
        if (!count($models)) {
            return array('code'=>'-1', 'msg'=>'没有数据');
        }
        $models = $this->jsonToArr($models);
        $dataArr = array();
        foreach ($models as $model) {
            //库视频信息
            $resStocks = DB::table($this->tStock)
                ->where('id',$model['vid'])
                ->orderBy('id','desc')
                ->skip(0)->take(1)
                ->get();
            $stockOne = count($resStocks) ? $this->jsonToArr($resStocks[0]) : '';
            $stockTitle = $stockOne ? $stockOne['fileTitle'] : '';
            $stockImg = $stockOne ? $stockOne['fileImg'] : '';
            $stockLink = $stockOne ? $stockOne['fileLink'] : '';
            $stockType = $stockOne ? $stockOne['fromType'] : '';
            //用户信息
            $resUser = $this->getUnameByUid($model['uid']);
            $dataArr[] = [
                'plusId' => $model['id'],
                'uid' => $model['uid'],
                'uname' => $resUser,
                'videoId' => $model['vid'],
                'videoTitle' => $stockTitle,
                'videoType' => $stockType,
                'videoImg' => $stockImg,
                'videoLink' => $stockLink,
            ];
        }
        return array('code'=>'0', 'msg'=>'获取成功', 'data'=>$dataArr, 'total'=>$queryTotal);
    }

    /**
     * APP，通过UID、VID，获验证有没有
     */
    public function getExistByPlus($uid,$vid)
    {
        //库
        $stocks = DB::table($this->tStock)->where('del',0)
            ->where('id',$vid)->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        $stockOne = count($stocks) ? $this->jsonToArr($stocks[0]) : '';
        //创单
        $pluss = DB::table($this->table)->where('del',0)
            ->where('uid',$uid)->where('vid',$vid)
            ->skip(0)->take(1)
            ->get();
        $plusOne = count($pluss) ? $this->jsonToArr($pluss[0]) : '';
        //创板
        $boards = DB::table($this->tBoard)->where('del',0)
            ->where('uid',$uid)->where('vid',$vid)
            ->where('isRender',1)
            ->orderBy('id','desc')
            ->skip(0)->take(1)
            ->get();
        $boardOne = count($boards) ? $this->jsonToArr($boards[0]) : '';
        $bid = $boardOne ? $boardOne['id'] : 0;
        //素材
        $sources = DB::table($this->tSource)->where('del',0)
            ->where('bid',$bid)
            ->orderBy('serial','asc')
            ->get();
        $sources = count($sources) ? $this->jsonToArr($sources) : array();
        $isExist = ($plusOne && $boardOne) ? 1 : 0;
        return array(
            'stockOne' => $stockOne,
            'plusOne' => $plusOne,
            'boardOne' => $boardOne,
            'sources' => $sources,
            'isExist' => $isExist,
        );
    }

    /**
     * APP创单增加
     * @param $uid 用户ID
     * @param $vid 首页视频ID
     */
    public function setAppAdd($exists,$uid,$uname,$vid)
    {
        if (!$uid || !$vid) {
            return array('code'=>'-1', 'msg'=>'参数错误');
        }
        $stockOne = $exists['stockOne'];
        $plusOne = $exists['plusOne'];
        $boardOne = $exists['boardOne'];
        $sources = $exists['sources'];
        $sourceNum = $stockOne ? $stockOne['plusNum'] : 0;
        $boardHtml = $stockOne ? $stockOne['boardHtml'] : '';
        //开启事务
        DB::beginTransaction();
        try {
            //更新创单
            if (!$plusOne) {
                $plusId = DB::table($this->table)
                    ->insertGetId([
                        'uid' => $uid,
                        'vid' => $vid,
                        'created_at' => time(),
                    ]);
            } else {
                $plusId = $plusOne['id'];
            }
            //更新创板
            if (!$boardOne) {
                $boardId = DB::table($this->tBoard)
                    ->insertGetId([
                        'uid' => $uid,
                        'vid' => $vid,
                        'plus' => $plusId,
                        'uname' => $uname,
                        'boardNum' => $sourceNum,
                        'boardHtml' => $boardHtml,
                        'isRender' => 1,
                        'created_at' => time(),
                    ]);
            } else {
                $boardId = $boardOne['id'];
            }
            //更新素材
            $sourceIds = array();
            if (!count($sources) && $sourceNum) {
                for ($i=1;$i<=$sourceNum;$i++) {
                    $sourceIds[] = DB::table($this->tSource)
                        ->insertGetId([
                            'uid' => $uid,
                            'vid' => $vid,
                            'plus' => $plusId,
                            'bid' => $boardId,
                            'serial' => $i,
                            'created_at' => time(),
                        ]);
                }
            }
            $dataArr = array(
                'plusId' => $plusId,
                'boardId' => $boardId,
                'sourceIds' => $sourceIds,
            );
            //提交事务
            DB::commit();
            return array('code'=>0, 'msg'=>'操作成功', 'data'=>$dataArr);
        } catch (\Exception $e) {
            //事务回滚
            DB::rollBack();
            return array('code'=>-1, 'msg'=>'操作失败：'.$e);
        }
    }
}